<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\CodeRequest;
use App\Http\Requests\ExchangeRequest;
use App\Models\Order;
use App\Models\Users;
use App\Models\UsersIntegral;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use OSS\OssClient;
use PDO;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
class UsersController extends BaseController
{
    /**
     * 用户信息详情
     */
    public function index(Request $request)
    {

        return $this->success(Users::with('grade')->where('id',request()->userId)->first());
    }

    /**
     * 修改用户信息
     */
    public function update(Request $request)
    {
        $params = $request->all();

        if(!empty($request->input('password'))){
            if($this->checkCode($request->get('phone'), $request->get('code'))){
                $request->merge(['password'=>bcrypt($request->password)]);
            }else{
                return $this->apiError('驗證碼錯誤');
            }
        }
         $params=$request->except(['code','phone']);
        //  dd($params);



        if (Users::where('id', $request->userId)->update($params)) return $this->success();

        return $this->apiError();
    }

    /**
     * 修改密碼
     */
    public function updatePassword(CodeRequest $request)
    {

        $params = $request->all();

        if ($this->checkCode($params['phone'], $params['code'])) {
            $res =  Users::where('id', \request()->userId)->update(['password' => bcrypt($params['password'])]);
            if ($res) return $this->success();
            return $this->apiError('修改失敗');
        } else {
            return $this->apiError('驗證碼錯誤');
        }
    }



    /**
     * 验证码
     */
    private function checkCode($phone, $code)
    {
        $res = Redis::get($phone);
        if (empty($res)) return false;
        if ($res != $code) return false;
        return true;
    }

    /**
     * 获取等级
     */
    public function grade()
    {
        return $this->success(UsersIntegral::get());
    }

    /**
     * 兑换优惠券
     */
    public function exchangeCoupon(ExchangeRequest $request)
    {
        $user=request()->userId;
        $coupon_id=$request->id;
        $users= DB::table('users')->where('id',$user)->first();
        $coupon=DB::table('coupon')->where('id',$coupon_id)->first();

        if(!$coupon) return $this->apiError('該優惠券已經失效！');

        if($users->integrate < $coupon->integral) {
            return $this->apiError('缺少積分');
        }

       $is_coupon= DB::table('coupon_users')->where('coupon_id',$coupon_id)->where('users_id',$user)->first();
       if($is_coupon) return $this->apiError('不能重複兌換該優惠券！');
        DB::beginTransaction();

        try{
            DB::table('coupon_users')->insert(['users_id'=>$user,'coupon_id'=>$coupon_id]);
            DB::table('users')->where('id',$user)->decrement('integrate',$coupon->integral);

            DB::table('record_integral')->insert([
                'integral'=>$coupon->integral,
                'users_id'=>$user,
                'type'=>1,
                'status'=>0,
                'created_at'=>strtotime(date('Y-m-d'))
            ]);
            DB::commit();
            return $this->success('兌換成功');
        }catch(Exception $e){
            DB::rollBack();
            return $this->apiError('兌換失敗');
        }


    }

    /**
     * 积分记录
     */
    public function recordIntegral(Request $request)
    {
       $data= DB::table('record_integral')->where('users_id',$request->userId)->orderBy('status')->orderBy('created_at','desc')->paginate($request->get('limit',10));
    //    $data= DB::table('record_integral')->where('users_id',$request->userId)->get()->map(function($value){
    //         return (array) $value;
    //    })->toArray();

         foreach($data as &$item){
            $item->created_at=date('Y/m/d',$item->created_at);
         }

       return $this->success($data);
    }

    /**二维码 */
    public function

    qr()
    {
        $user=request()->userId;
        $filename = rand(10000, 99999) . time() . '.png';
        $base_name=config('services.basics.base_name');
        $users=DB::table('users')->where('id',$user)->first();
        $name=$base_name.":" . $users->id;

        $data=  QrCode::format('png')->encoding('UTF-8')->size(100)->generate($name,$filename);
        $uploadQRcode= $this->uploadQRcode($filename);
        $res=get_object_vars($uploadQRcode)['original'];

        if ($res['code']==200) {
            @unlink($filename);
            DB::table('users')->where('id',$user)->update(['qrcode'=>$res['data']['file_path']]);
            return $this->success($res['data']);
        } else {
            return $this->success(["file_path" => '']);
        }

    }
    /**
     * 订单二维码
     */
    public function orderQr(Request $request)
    {
        $order_id=$request->get('order_id');
        $user=$request->userId;
      $order=  Order::where('users_id',$user)->where('id',$order_id)->first();
      $filename = rand(10000, 99999) . time() . '.png';
      $data=  QrCode::format('png')->encoding('UTF-8')->size(100)->generate($order->order_no,$filename);
      $uploadQRcode= $this->uploadQRcode($filename);
      $res=get_object_vars($uploadQRcode)['original'];

      if ($res['code']==200) {
          @unlink($filename);
          DB::table('users')->where('id',$user)->update(['qrcode'=>$res['data']['file_path']]);
          return $this->success($res['data']);
      } else {
          return $this->success(["file_path" => '']);
      }
    }

     /**
     * @param $filename
     * @return array
     * 上傳二維碼
     */
    protected function uploadQRcode($filename)
    {
        $accessKeyId = "LTAI4G2Np2fQbQ4SqfZbqXk7";
        $accessKeySecret = "eqtOSuDazSrLSPKTc0IZjMcrJfFjmE";
        $endpoint = "oss-cn-hongkong.aliyuncs.com";
        // 存储空间名称
        $bucket = "brain-storm";
        $object = 'ewm/' . $filename;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filename);
            return $this->success(["file_path" => 'https://brain-storm.oss-cn-hongkong.aliyuncs.com/' . $object]);
        } catch (Exception $e) {
            return $this->Error($e);
        }
    }


    public function delete(Request $request)
    {
       DB::table('users')->where('id',request()->userId)->delete();
        return $this->success();
    }
}
